package com.itheima.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.dto.SysMenuDto;
import com.itheima.ydd.entity.SysMenu;
import com.itheima.ydd.mapper.SysMenuMapper;
import com.itheima.ydd.service.ISysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Override
    public List<SysMenuDto> allData() {
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysMenu::getPid, 0);
        //查询到父级id
        List<SysMenu> list = this.list(queryWrapper);
        //存放数据
        List<SysMenuDto> sysMenuDtos = new ArrayList<>();

        for (SysMenu sysMenu : list) {
            SysMenuDto sysMenuDto = new SysMenuDto();
            //将父级数据拷贝到sysmenudto中
            BeanUtils.copyProperties(sysMenu, sysMenuDto);
            LambdaQueryWrapper<SysMenu> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(SysMenu::getPid, sysMenu.getId());
            //查询子菜单
            List<SysMenu> menuList = this.list(queryWrapper1);
            List<SysMenuDto> sysMenuDtos2 = new ArrayList<>();

            for (SysMenu menu : menuList) {
                SysMenuDto sysMenuDto2 = new SysMenuDto();
                //将子级数据拷贝到孙子级数据中
                BeanUtils.copyProperties(menu, sysMenuDto2);
                LambdaQueryWrapper<SysMenu> queryWrapper2 = new LambdaQueryWrapper<>();
                queryWrapper2.eq(SysMenu::getPid, menu.getId());
                //查询孙子级的数据
                List<SysMenu> sysMenuList = this.list(queryWrapper2);
                sysMenuDto2.setChildren(sysMenuList);
                sysMenuDtos2.add(sysMenuDto2);
            }
            sysMenuDto.setChildren(sysMenuDtos2);
            sysMenuDtos.add(sysMenuDto);
        }
        return sysMenuDtos;
    }
}
